import React, { useState, FC, useRef } from 'react'
import { Select, Spin } from 'antd'
import debounce from 'lodash/debounce'
import './index.less'

const { Option } = Select

interface IProps {
  placeSearch: any
  callback?: Function
}

const ToolSearch: FC<IProps> = ({ placeSearch, callback }: IProps) => {
  const [value, setValue] = useState<string | undefined>(undefined)
  const [fetching, setFetching] = useState(false)
  const [data, setData] = useState<any[]>([])
  const lastFetchId = useRef(0)

  const fetchPoints = (value: string) => {
    lastFetchId.current++
    const fetchId = lastFetchId.current
    setData([])
    setFetching(true)
    placeSearch.search(value, (status: any, result: any) => {
      if (fetchId !== lastFetchId.current) {
        return
      }
      if (status === 'complete') {
        setData(result?.poiList?.pois ?? [])
        setFetching(false)
      }
    })
  }

  const _fetchPoints = debounce(fetchPoints)

  const handleChange = (value: string) => {
    setFetching(false)
    setValue(value)
    setData([])
  }

  if (!placeSearch) {
    return <></>
  }

  const Spiner = (
    <>
      <Spin size="small" /> 搜索中...
    </>
  )

  const handleSelect = (value: any) => {
    const item = data.find((item) => item.name === value)
    item && callback && callback(item)
  }

  return (
    <Select
      className="search"
      value={value}
      placeholder="搜索地点"
      notFoundContent={fetching ? Spiner : null}
      filterOption={false}
      showSearch
      onSearch={_fetchPoints}
      onChange={handleChange}
      onSelect={handleSelect}
    >
      {data?.map((item) => (
        <Option key={item.id} value={item.name}>
          {item.name}
        </Option>
      ))}
    </Select>
  )
}

export default ToolSearch
